import axios from "axios";
import $api from "@/config";

axios.defaults.baseURL = $api.baseURL()
axios.defaults.timeout = 30000
console.log('当前请求地址：',axios.defaults.baseURL)

//添加token
axios.interceptors.request.use(
    config => {
        let token = 'eyJhbGciOiJIUzI1NiJ9.eyJVc2VyRGF0YSI6eyJ1c2VySWQiOiI3YTFkNjU2NjgxYjc1YzNmYTExNDdkYjc4OWFkNWRlNiIsInVzZXJOYW1lIjoi5p2O5ZubIiwidG9rZW4iOm51bGx9fQ.7IMC_xpRPL6j7MwHRlpxsICP2eaKt5NkPRM76xD4yvU'
        if (token) {
            config.headers['token'] = token
        }
        return config
    }
)

//统一处理报错
axios.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return Promise.resolve(response);
        }else {
            // alert('请求失败')
        }
    },
    error => {
        if (error) {
            //截取报错文字
            let errorMsg = error.toString()
            // alert(errorMsg)
        }
    }
)
export const get = (url,query) => {
    return new Promise((resolve,reject)=>{
        axios.get(url,{params:query}).then(res=>{
            resolve(res.data)
        }).catch(err=>{
            reject(err)
        })
    })
}

export const put = (url,params) => {
    return new Promise((resolve,reject)=>{
        axios.put(url,params).then(res=>{
            resolve(res.data)
        }).catch(err=>{
            reject(err)
        })
    })
}

export const Delete = (url,params) => {
    return new Promise((resolve,reject)=>{
        axios.delete(url+'/'+params).then(res=>{
            resolve(res.data)
        }).catch(err=>{
            reject(err)
        })
    })
}

export const post = (url,params)=>{
    return new Promise((resolve, reject)=>{
        axios.post(url,params,{
            headers:{'Content-Type': 'application/json;charset=UTF-8'}
        }).then(res=>{
            resolve(res.data)
        }).catch(err=>{
            reject(err)
        })
    })
}

export const postFormData = (url,params)=>{
    return new Promise((resolve, reject) => {
        axios.post(url,params,{
            headers: {'Content-Type':'multipart/form-data'}
        }).then(res=>{
            resolve(res.data)
        }).catch(err=>{
            reject(err)
        })
    })
}

export const getTemplate = (url,query)=>{
    return new Promise((resolve, reject) => {
        axios.get(url,{params:query,responseType:'arraybuffer'}).then(res=>{
            const blob = new Blob([res.data],{type:'application/vnd.ms-excel'})
            resolve(blob)
        }).catch(err=>{
            reject(err)
        })
    })

}
//傻逼后端非要用post请求下载excel，死了🐎，自己偷懒把屎留给前端擦，可能户口本比较厚吧，所以只有另外封装一个post/blob类型的请求方法,这个公司的后端都不是标准后端，对象属性名能返中文的你说是什么牛马？
export const postTemplate = (url,params)=>{
    return new Promise((resolve, reject) => {
        axios.post(url,params,{responseType:'arraybuffer'}).then(res=>{
            const blob = new Blob([res.data],{type:'application/vnd.ms-excel'})
            resolve(blob)
        }).catch(err=>{
            reject(err)
        })
    })

}

